﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Server
{
    class ServerStart
    {

        private const int port = 17333;
        static void Main(string[] args)
        {
            // CreateTCPServer();
            CreateUDPServer();
            Console.ReadKey();

        }

        static void CreateUDPServer() 
        {
            UdpClient listener = new UdpClient(port);
            IPEndPoint remoteIP = new IPEndPoint(IPAddress.Any, port);

            try
            {
                while (true)
                {
                    Console.WriteLine("waiting  for message");
                    byte[] bytes = listener.Receive(ref remoteIP);
                    Console.WriteLine($"recived msg from{remoteIP}");
                    Console.WriteLine($"{Encoding.ASCII.GetString(bytes, 0, bytes.Length)}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally 
            {
                listener.Close();
            }

        }

        static void CreateTCPServer() 
        {
            TcpListener listener = new TcpListener(IPAddress.Any,port);
            listener.Start();
            Console.WriteLine("waiting for connection....");
            while (true)
            {
                TcpClient client = listener.AcceptTcpClient();
                Console.WriteLine("Connection accepted.");
                NetworkStream ns = client.GetStream();
                byte[] data = Encoding.ASCII.GetBytes("www.q");
                try
                {
                    ns.Write(data, 0, data.Length);
                    ns.Close();

                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
    }
}
